package com.xunqi.shiro.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //1.自定义的Realm
    @Bean
    public Realm realm(){
        return new MyRealm();
    }

    //2.根据注入的realm创建一个安全管理器
    @Bean
    public SecurityManager securityManager(Realm realm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        return securityManager;
    }

    //3.定义进行安全拦截的过滤器和规则ShiroFilterFactroyBean
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        /*
         * anon 无需授权直接访问
         * authc 需要授权
         * perms 指定权限
         * users  如果使用记住我可免
         */
        Map<String,String> map = new LinkedHashMap<String, String>();
        map.put("/toLogin","anon");     //登录页面免认证
        //映射【资源】和【权限】的关系
        map.put("/user/add","perms[user/add]");
        map.put("/user/update","perms[user/update]");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        shiroFilterFactoryBean.setLoginUrl("/toLogin");     //设置登录页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/user/noAuth");  //设置未授权时要显示的页面

        shiroFilterFactoryBean.setSecurityManager(securityManager);
        return shiroFilterFactoryBean;
    }

    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }

}
